<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="default" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="流程编码" prop="flowCode">
        <el-input v-model="queryParams.flowCode" placeholder="请输入流程编码" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="流程名称" prop="flowName">
        <el-input v-model="queryParams.flowName" placeholder="请输入流程名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="流程类别" prop="category">
        <el-input v-model="queryParams.category" placeholder="请输入流程类别" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="流程版本" prop="version">
        <el-input v-model="queryParams.version" placeholder="请输入流程版本" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" size="default" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" size="default" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" size="default" @click="handleAdd"
          v-hasPermi="['flow:definition:add']">新增</el-button>
        <el-button type="primary" plain icon="Plus" size="default" @click="handleImport"
          v-hasPermi="['flow:definition:importDefinition']">导入流程定义</el-button>
      </el-col>
      <right-toolbar :showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="definitionList" @selection-change="handleSelectionChange"
      @sort-change="handleSortChange">
      <el-table-column type="selection" width="55" align="center" fixed />
      <el-table-column label="序号" width="50" align="center" key="id" prop="id">
        <template #default="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="流程编码" align="center" prop="flowCode" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="流程名称" align="center" prop="flowName" :show-overflow-tooltip="true" />
      <el-table-column label="流程版本" align="center" prop="version" width="100" :show-overflow-tooltip="true">
        <template #default="scope">
          <el-tag>{{scope.row.version}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="流程类别" align="center" prop="category" :show-overflow-tooltip="true" />
      <el-table-column label="是否发布" align="center" prop="isPublish" width="140" :show-overflow-tooltip="true">
        <template #default="scope">
          <dict-tag :options="isPublish" :value="scope.row.isPublish" />
        </template>
      </el-table-column>
      <el-table-column label="激活状态" align="center" prop="activityStatus" width="140" :show-overflow-tooltip="true">
        <template #default="scope">
          <dict-tag :options="activityStatus" :value="scope.row.activityStatus" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160"
        :sort-orders="['descending', 'ascending']" :show-overflow-tooltip="true">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" fixed="right" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button type="primary" size="small" link @click="handleDesign(scope.row.id, scope.row.isPublish)"
            v-hasPermi="['flow:definition:queryDesign']">流程设计</el-button>
          <el-button type="primary" size="small" link v-if="scope.row.isPublish === 0"
            @click="handlePublish(scope.row.id)" v-hasPermi="['flow:definition:publish']">发布</el-button>
          <el-button type="primary" size="small" link v-if="scope.row.isPublish === 1"
            @click="handleUpPublish(scope.row.id)" v-hasPermi="['flow:definition:upPublish']">取消发布</el-button>
          <el-button type="primary" size="small" link v-if="scope.row.activityStatus === 0"
            @click="toActive(scope.row.id)">激活</el-button>
          <el-button type="primary" size="small" link v-if="scope.row.activityStatus === 1"
            @click="toUnActive(scope.row.id)">挂起</el-button>
          <el-button type="primary" size="small" link @click="handleCopyDef(scope.row.id)"
            v-hasPermi="['flow:definition:copy']">复制流程</el-button>
          <el-button type="primary" size="small" link @click="handleExport(scope.row)"
            v-hasPermi="['flow:definition:exportDefinition']">导出流程</el-button>
          <el-button type="primary" size="small" link v-if="scope.row.isPublish === 0" @click="handleDelete(scope.row)"
            v-hasPermi="['flow:definition:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadRef" multiple :limit="20" accept=".json" :headers="upload.headers" :action="upload.url"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
        :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入json格式文件。</span>
        </div>
      </el-upload>
      <template #footer>
        <el-button @click="upload.open = false">取 消</el-button>
        <el-button type="primary" @click="submitFileForm" :loading="upload.isUploading">
          确 定
        </el-button>
      </template>
    </el-dialog>

    <el-dialog title="流程图" v-model="flowChart" width="80%">
      <img :src="imgUrl" width="100%" style="margin:0 auto" />
    </el-dialog>
  </div>
</template>

<script setup>
  import {
    ref,
    onMounted
  } from 'vue'
  import {
    useRouter
  } from 'vue-router'
  import {
    listDefinition,
    delDefinition,
    publish,
    unPublish,
    copyDef,
    active,
    unActive
  } from '@/api/flow/definition'
  import {
    getToken
  } from '@/utils/auth'
  import {
    parseTime
  } from '@/utils/ruoyi'
  import {
    download
  } from '@/utils/request'
  import {
    ElMessageBox
  } from 'element-plus'
  const queryForm = ref(null)
  const uploadRef = ref(null)
  const router = useRouter()
  // 遮罩层
  const loading = ref(true)
  const imgUrl = ref("")
  const flowChart = ref(false)
  // 唯一标识符
  const uniqueId = ref("")
  // 选中数组
  const ids = ref([])
  // 非单个禁用
  const single = ref(true)
  // 非多个禁用
  const multiple = ref(true)
  // 显示搜索条件
  const showSearch = ref(true)
  // 总条数
  const total = ref(0)
  // 流程定义表格数据
  const definitionList = ref([])
  // 查询参数
  const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
    flowCode: null,
    flowName: null,
    version: null,
  })
  // 用户导入参数
  const upload = ref({
    // 是否显示弹出层（用户导入）
    open: false,
    // 弹出层标题（用户导入）
    title: "",
    // 是否禁用上传
    isUploading: false,
    // 设置上传的请求头部
    headers: {
      Authorization: "Bearer " + getToken()
    },
    // 上传的地址
    url: import.meta.env.VITE_APP_BASE_API + "/flow/definition/importDefinition"
  })
  const isPublish = ref([{
      label: '未发布',
      value: '0'
    },
    {
      label: '已发布',
      value: '1'
    },
    {
      label: '失效',
      value: '9'
    }
  ]);
  const activityStatus = ref([{
      label: '挂起',
      value: '0'
    },
    {
      label: '激活',
      value: '1'
    }
  ]);
  // 查询流程定义列表
  const getList = () => {
    loading.value = true
    listDefinition(queryParams.value).then(response => {
      console.log(response)
      definitionList.value = response.rows
      total.value = Number(response.total)
      loading.value = false
    })
  }

  // 搜索按钮操作
  const handleQuery = () => {
    queryParams.value.pageNum = 1
    getList()
  }
  // 重置表单方法（适配组合式 API）
  const resetForm = () => {
    if (queryForm.value) { // 直接通过 ref 变量访问表单实例
      queryForm.value.resetFields() // 调用 Element Plus 的重置方法
    }
  }
  // 重置按钮操作
  const resetQuery = () => {
    resetForm("queryForm")
    handleQuery()
  }

  // 多选框选中数据
  const handleSelectionChange = (selection) => {
    ids.value = selection.map(item => item.id)
    single.value = selection.length !== 1
    multiple.value = !selection.length
  }

  // 新增按钮操作
  const handleAdd = () => {
    const params = {
      disabled: false,
      pageNum: queryParams.value.pageNum
    }
    router.push({
      path: '/flow/flow-design/index',
      query: params
    })
  }

  // 流程设计按钮操作
  const handleDesign = (id, isPublish) => {
    const params = {
      disabled: isPublish === 1,
      pageNum: queryParams.value.pageNum
    }
    router.push({
      path: `/flow/flow-design/index/${id}`,
      query: params
    })
  }

  // 发布按钮操作
  const handlePublish = (id) => {
    ElMessageBox.confirm('是否确认发布流程定义编号为"' + id + '"的数据项？').then(() => {
      return publish(id)
    }).then(() => {
      getList()
      ElMessage.success("发布成功")
    }).catch(() => {})
  }

  // 取消发布按钮操作
  const handleUpPublish = (id) => {
    ElMessageBox.confirm('是否确认取消发布流程定义编号为"' + id + '"的数据项？').then(() => {
      return unPublish(id)
    }).then(() => {
      getList()
      ElMessage.success("取消成功")
    }).catch(() => {})
  }

  // 删除按钮操作
  const handleDelete = (row) => {
    const deleteIds = row.id || ids.value
    ElMessageBox.confirm('是否确认删除流程定义编号为"' + deleteIds + '"的数据项？').then(() => {
      return delDefinition(deleteIds)
    }).then(() => {
      getList()
      ElMessage.success("删除成功")
    }).catch(() => {})
  }

  // 复制流程按钮操作
  const handleCopyDef = (id) => {
    ElMessageBox.confirm('是否确认复制流程定义编号为"' + id + '"的数据项？').then(() => {
      return copyDef(id)
    }).then(() => {
      getList()
      ElMessage.success("复制成功")
    }).catch(() => {})
  }

  // 导入按钮操作
  const handleImport = () => {
    upload.value = {
      ...upload.value,
      title: "用户导入",
      open: true,
      isUploading: false // 重置上传状态
    }
  }

  const handleExport = (row) => {
    download('/flow/definition/exportDefinition/' + row.id, {
      ...queryParams.value
    }, row.flowCode + '_' + row.version + '.json')
  }

  // 文件上传中处理
  const handleFileUploadProgress = (event, file, fileList) => {
    upload.value.isUploading = true
  }

  // 文件上传成功处理
  const handleFileSuccess = (response, file, fileList) => {
    // 1. 更新上传状态
    upload.value.open = false
    upload.value.isUploading = false
    // 2. 清空已上传文件（使用正确的ref引用）
    uploadRef.value?.clearFiles()
    // 3. 显示结果提示
    ElMessageBox.alert(
      `<div style="overflow: auto; overflow-x: hidden; max-height: 70vh; padding: 10px 20px 0;">
      ${response.msg}
    </div>`,
      "导入结果", {
        dangerouslyUseHTMLString: true
      }
    )
    // 4. 刷新列表数据
    getList()
  }

  // 提交上传文件
  const submitFileForm = () => {
    uploadRef.value.submit()
  }

  // 排序触发事件
  const handleSortChange = (column, prop, order) => {
    queryParams.value.orderByColumn = column.prop
    queryParams.value.isAsc = column.order
    getList()
  }

  const toActive = (id) => {
    ElMessageBox.confirm('是否确认激活流程定义编号为"' + id + '"的数据项？').then(() => {
      return active(id)
    }).then(() => {
      getList()
      ElMessage.success("激活成功")
    }).catch(() => {})
  }

  const toUnActive = (id) => {
    ElMessageBox.confirm('是否确认挂起流程定义编号为"' + id + '"的数据项？').then(() => {
      return unActive(id)
    }).then(() => {
      getList()
      ElMessage.success("挂起成功")
    }).catch(() => {})
  }

  onMounted(() => {
    getList()
    const time = router.currentRoute.value.query.t
    if (time != null && time != uniqueId.value) {
      uniqueId.value = time
      queryParams.value.pageNum = Number(router.currentRoute.value.query.pageNum)
      getList()
    }
  })
</script>